var redis = require('redis');
var redisClient = redis.createClient();
var config = require('./../config.json');

module.exports = (function() {
    var express = require('express');
    var router = express.Router();
    var request = require('request');
    router.get('/:forceRefresh?/:type?', function(req, res) {
        var url = config.apiUrl;
        var forceRefresh = req.params.forceRefresh === undefined ? false : (req.params.forceRefresh === 'true');
        var type = req.params.type === undefined ? 'MetroMonitor' : req.params.type;

        var redisProjectsKey = {
            MetroMonitor: 'metroProjects:projects',
            RoadTunnellMonitor: 'metroProjects:roadProjects',
            CriticalSectionMonitor: 'metroProjects:criticalProjects'
        };

        console.log("force projects in redis Refresh is %s", !forceRefresh ? 'false' : 'true');
        
        var redisKey = redisProjectsKey[type];
        if (forceRefresh) {
            redisClient.del(redisKey, function(req, reply) {
                console.log(reply);
                getProjects(redisKey, type);
            });
        } else {
            getProjects(redisKey, type);
        }

        function getProjects(redisKey, type) {
            redisClient.get(redisKey, (function(req, res) {
                return function(err, reply) {
                    if (!reply) {
                        request({
                            url: url + '/projects/',
                            qs: {
                                type: type
                            }
                        }, function(error, response, body) {
                            if (!error && response.statusCode == 200) {
                                redisClient.set(redisKey, body, redis.print);
                                res.send(JSON.parse(body));
                            } else {
                                res.send('fail to load!');
                            }
                        });
                    } else {
                        // reply = JSON.parse(reply);
                        res.send(JSON.parse(reply));
                    }
                    // redisClient.quit();
                };
            })(req, res));
        }
    });
    return router;
})();
